package com.happy3w.task.composer;

import java.util.List;
import java.util.function.Function;

public class FunctionTask extends Task {
    private final TaskDataMode inputMode;
    private final TaskDataMode outputMode;
    private final Function taskAction;

    public FunctionTask(List<TaskDataDef> inputs, TaskDataMode inputMode,
                        List<TaskDataDef> outputs, TaskDataMode outputMode,
                        Function taskAction) {
        super(inputs, outputs);
        this.inputMode = inputMode;
        this.outputMode = outputMode;
        this.taskAction = taskAction;
    }

    public static FunctionTask from(Function taskAction, List<TaskDataDef> inputs, TaskDataMode inputMode, List<TaskDataDef> outputs, TaskDataMode outputMode) {
        return new FunctionTask(inputs, inputMode,
                outputs, outputMode,
                taskAction);
    }

    @Override
    public void execute(TaskExecuteContext context) {
        Object params = inputMode.createParams(inputs, context);
        Object result = taskAction.apply(params);
        outputMode.saveResult(result, outputs, context);
    }
}
